<template>
  <div class="contrast-box growth">
    <div class="contrast">
      <div class="c-main-box-box">
        <div class="c-main-box">
          <div class="c-main">
            <div class="c-left">
              <div class="filter-box">
                <div class="title-date">
                  <h3 class="title">
                    <em></em>园所
                    <span>身体发育</span>横向对比</h3>
                </div>
                <div class="float">
                  <h3>性别选择（单选）</h3>
                  <el-radio :tabList="sex" @getRadio="getRadio(arguments, 211.1)"></el-radio>
                </div>
              </div>
              <div class="echarts-box">
                <div>
                  <h3 class="pointTitle iconfont">平均身高</h3>
                  <bar v-if="averageHeight.summary !== '暂无总结'" :settings="averageHeight"></bar>
                  <no-data v-else :item="'平均身高'" />
                  <el-summary :data="averageHeight.summary"></el-summary>
                </div>
                <div>
                  <h3 class="pointTitle iconfont">平均体重</h3>
                  <bar v-if="averageWeight.summary !== '暂无总结'" :settings="averageWeight"></bar>
                  <no-data v-else :item="'平均体重'" />
                  <el-summary :data="averageWeight.summary"></el-summary>
                </div>
              </div>
            </div>
            <div class="c-right">
              <div class="filter-box">
                <div class="title-date">
                  <h3 class="title">
                    <em></em>园所儿童
                    <span>身体发育</span>纵向对比</h3>
                  <ul>
                    <li class="btn1" @click="timeSlot(90, 212)">最近3个月</li>
                  </ul>
                </div>
                <div class="float">
                  <h3>性别选择（单选）</h3>
                  <el-radio :tabList="sex" @getRadio="getRadio(arguments, 212.1)"></el-radio>
                </div>
                <div class="float">
                  <h3>年级选择（单选）</h3>
                  <el-radio :tabList="grade" @getRadio="getRadio(arguments, 212.2)"></el-radio>
                </div>
              </div>
              <div class="echarts-box">
                <pie3 :data="dataList"></pie3>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import { mapGetters } from 'vuex'
import ElCheckbox from '@/common/elementUi/ElCheckbox'
import DatePicker from '@/common/elementUi/EldatePicker'
import ElRadio from '@/common/elementUi/ElRadio'
import ElLine from '@/common/echarts/Line'
import MonthRange from '@/common/layerUi/MonthRange'
import Bar from '@/common/echarts/Bar'
import Pie3 from '@/common/echarts/expand/Pie3'
import { timeSlot } from '@/common/customTime/customTime'
import Bars from '@/common/echarts/expand/Bars'
import ElSummary from '@/common/summary/Summary'
export default {
  name: 'HealthyContrast',
  components: {
    ElCheckbox,
    DatePicker,
    ElRadio,
    ElLine,
    MonthRange,
    Bar,
    Pie3,
    ElSummary
  },
  data () {
    return {
      // 首次登陆
      isOnce: true,
      // 身体发育横向对比
      growthC: {
        time: {
          startTime: '2018-07-29',
          endTime: '2018-07-30'
        },
        sex: '男童',
        grade: '托班',
        data: []
      },
      // 身体发育横向对比
      growthL: {
        time: {
          startTime: '2018-07-29',
          endTime: '2018-07-30'
        },
        sex: '男童',
        grade: '托班',
        data: []
      },
      sex: ['男童', '女童'],
      grade: ['托班', '小班', '中班', '大班'],
      // 平均身高
      averageHeight: {
        xData: ['暂无数据'],
        data: [0],
        linearGradient: ['#33b3b7', '#53e9ee'],
        yName: '身高（cm）',
        labelHide: true,
        labelNuit: '{c}cm',
        grid: {
          top: '18%',
          left: '0%',
          right: '0%',
          bottom: '0%',
          containLabel: true
        },
        summary: '...'
      },
      // 平均体重
      averageWeight: {
        xData: ['暂无数据'],
        data: [0],
        linearGradient: ['#d0bb66', '#ffe98f'],
        yName: '体重（kg）',
        labelHide: true,
        labelNuit: '{c}kg',
        grid: {
          top: '18%',
          left: '0%',
          right: '0%',
          bottom: '0%',
          containLabel: true
        },
        summary: '...'
      },
      // 身体发育横向对比
      dataList: [
        {
          title: '2018-06月',
          data: [
            { value: 0, name: '偏轻' },
            { value: 0, name: '均值' },
            { value: 0, name: '肥胖' },
            { value: 0, name: '超重' }
          ]
        },
        {
          title: '2018-07月',
          data: [
            { value: 0, name: '偏轻' },
            { value: 0, name: '均值' },
            { value: 0, name: '肥胖' },
            { value: 0, name: '超重' }
          ]
        },
        {
          title: '2018-08月',
          data: [
            { value: 0, name: '偏轻' },
            { value: 0, name: '均值' },
            { value: 0, name: '肥胖' },
            { value: 0, name: '超重' }
          ]
        }
      ]
    }
  },
  mounted () {
    // 初始化所有边框样式
    this.$common.border(window.$('.contrast'))
    this.timeSlot(7, 211)
    this.timeSlot(90, 212)
    window.$('.title-date li').click(function () {
      window.$(this).closest('li').addClass('on').siblings().removeClass('on')
    })
  },
  watch: {
    // 出勤情况横向对比
    'growthC.time': {
      deep: true,
      handler: function () {
        this.getGrowthC()
      }
    },
    'growthC.sex': {
      deep: true,
      handler: function () {
        this.dayGrowthC()
      }
    },
    'growthC.grade': {
      deep: true,
      handler: function () {
        this.dayGrowthC()
      }
    },
    'growthL.time': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    },
    'growthL.sex': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    },
    'growthL.grade': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    }
  },
  computed: {
    provinceId () { return this.$store.getters.crumbIds.province },
    cityId () { return this.$store.getters.crumbIds.city },
    districtId () { return this.$store.getters.crumbIds.district },
    gardenName () { return this.$store.getters.crumbs.garden },
    gardenId () { return this.$store.getters.crumbIds.garden },
    ...mapGetters({
      // 区域等级
      areaLevel: 'areaLevel',
      // 选择对比项
      cityList: 'areaMapList'
    })
  },
  methods: {
    getGrowthC () {
      //  const avgData = { gid: 7006, sdate: '2018-05-01', edate: '2018-08-31' }
      // console.log(avgData)
      // window.$.ajax({
      //   url: 'http://api.youjiaoyun.net/weixin.asmx/GetGardenAvgDataList?jsoncallback=?',
      // let data = {}
      const StartDate = this.growthC.time.startTime + ' 00:00:01'
      const EndDate = this.growthC.time.endTime + ' 23:59:59'
      // const data = { gid: 7006, sdate: StartDate, edate: EndDate }
      window.$.ajax({
        url: 'http://api.youjiaoyun.net/weixin.asmx/GetGardenAvgDataList?jsoncallback=?',
        dataType: 'jsonp',
        data: {
          sdate: StartDate,
          edate: EndDate,
          gid: this.gardenId,
        },
        jsonp: 'jsoncallback',
        async: false,
        success: (res) => {
          this.growthC.data = res
          this.dayGrowthC()
        }
      })
    },
    dayGrowthC () {
      const res = this.growthC.data
      console.log(res)
      const $data = []
      let summary1 = ''
      let summary2 = ''
      if (res.length) {
        for (let i = 0, len = res.length; i < len; i++) {
          // 女高, 女重, 男高, 男重
          let sum = [[], [], [], []]
          for (let j = 0, len = res[i].classdatas.length; j < len; j++) {
            if (res[i].classdatas[j].datas.length) {
              // debugger
              console.log(res[2].classdatas[0].datas)
              const sex0 = res[i].classdatas[j].datas.filter((p) => { return p.sex === 0 })
              console.log(sex0)
              const sex1 = res[i].classdatas[j].datas.filter((p) => { return p.sex === 1 })
              console.log(sex1)
              if (sex0.length) {
                sum[0].push(sex0[0].ClassAvgHeight)
                sum[1].push(sex0[0].ClassAvgWeight)
              } else {
                sum[0].push(0)
                sum[1].push(0)
              }
              if (sex1.length) {
                sum[2].push(sex1[0].ClassAvgHeight)
                sum[3].push(sex1[0].ClassAvgWeight)
              } else {
                sum[2].push(0)
                sum[3].push(0)
              }
            }
          }
          console.log(sum,'sum')
          sum = sum.map((p) => {
            let pSum = 0
            if (p.length) {
              for (let i = 0, len = p.length; i < len; i++) {
                pSum += p[i]
              }
              return pSum / p.length
            } else {
              return 0
            }
          })
          console.log($data)
          $data.push({
            name: res[i].GradeName,
            '女童': {
              height: sum[0],
              weight: sum[1]
            },
            '男童': {
              height: sum[2],
              weight: sum[3]
            }
          })
        }
        console.log($data)
        const newData = $data.filter((item) => {
          return item.name && (item["女童"].height || item["男童"].height)
        })
        console.log(newData,'newData')
        if (newData.length) {
          newData.sort((p1, p2) => {
            return (p2["男童"].height + p2["女童"].height) - (p1["男童"].height + p1["女童"].height)
          })
          let sexv = this.growthC.sex
          const arr = {
            name: [],
            value: {
              height: [],
            }
          }
          for (let i = 0; i < newData.length; i++) {
            arr.name.push(newData[i].name)
            arr.value.height.push((newData[i][sexv].height).toFixed(2))
          }
          this.averageHeight.xData = arr.name
          this.averageHeight.data = arr.value.height
          summary1 = `在截至计算时间内,该园所身体发育如下: <br>平均身高最高: ${newData[0].name} 平均身高最矮:${newData[newData.length - 1].name}`
          this.averageHeight.summary = summary1
        } else {
          this.averageHeight.xData = ['暂无数据']
          this.averageHeight.data = ['0']
          this.averageHeight.summary = '暂无总结'
        }
        console.log($data)
        const newDataWeight = $data.filter((item) => {
          return item.name && (item["女童"].weight || item["男童"].weight)
        })
        if (newDataWeight.length) {
          newDataWeight.sort((p1, p2) => {
            return (p2["男童"].weight + p2["女童"].weight) - (p1["男童"].weight + p1["女童"].weight)
          })
        let sexv = this.growthC.sex
          const arr1 = {
            name: [],
            value: {
              weight: []
            }
          }
          for (let i = 0; i < newDataWeight.length; i++) {
            arr1.name.push(newDataWeight[i].name)
            arr1.value.weight.push((newDataWeight[i][sexv].weight).toFixed(2))
          }
          this.averageWeight.xData = arr1.name
          this.averageWeight.data = arr1.value.weight
          summary2 = `在截至计算时间内,该园所身体发育如下: <br>平均体重最重: ${newDataWeight[0].name} 平均体重最轻:${newDataWeight[newDataWeight.length - 1].name}`
          this.averageWeight.summary = summary2
        } else {
          this.averageWeight.xData = ['暂无数据']
          this.averageWeight.data = ['0']
          this.averageWeight.summary = '暂无总结'
        } 
        } else {
        this.averageHeight.xData = ['暂无数据']
        this.averageHeight.data = ['0']
        this.averageHeight.summary = '暂无总结'
        this.averageWeight.xData = ['暂无数据']
        this.averageWeight.data = ['0']
        this.averageWeight.summary = '暂无总结'
      }
    },
    getMonthDays (myMonth) {
      let now = new Date()
      let nowYear = now.getYear()
      nowYear += (nowYear < 2000) ? 1900 : 0
      const monthStartDate = new Date(nowYear, myMonth, 1)
      const monthEndDate = new Date(nowYear, myMonth + 1, 1)
      const days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
      return days
    },
    // 身体发育纵向对比
    getGrowthL () {
      this.dataList = [
        {
          title: '',
          data: []
        },
        {
          title: '',
          data: []
        },
        {
          title: '',
          data: []
        }
      ]
      const date = new Date()
      let time = date.getMonth()
      // 当月
      let day = this.getMonthDays(time)
      let StartDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-01'
      let EndDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 0)
      // 上月
      day = this.getMonthDays(time - 1)
      StartDate = date.getFullYear() + '-' + (date.getMonth()) + '-01'
      EndDate = date.getFullYear() + '-' + (date.getMonth()) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 1)
      // 上上月
      day = this.getMonthDays(time - 2)
      StartDate = date.getFullYear() + '-' + (date.getMonth() - 1) + '-01'
      EndDate = date.getFullYear() + '-' + (date.getMonth() - 1) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 2)
    },
    GetGrowthL (StartDate, EndDate, idx) {
      let data = { ProvinceId: this.provinceId, CityId: this.cityId, DistrictId: this.districtId, Gid: this.gardenId, IsMonth: true, StartDate: StartDate, EndDate: EndDate }
      window.$.ajax({
        url: 'http://api.youjiaoyun.net/weixin.asmx/GetBodyCheckResultList?jsoncallback=?',
        dataType: 'jsonp',
        data: data,
        jsonp: 'jsoncallback',
        async: false,
        success: (res) => {
          this.growthL.data = res
          this.MonthGrowthL(StartDate, idx)
        }
      })
    },
    avgHW (res, sex, gid) {
      let arr = []
      let BMI = res.filter((item) => {
        return item.Gender === sex && item.Gid === gid
      })
      BMI = this.$common.compare(BMI, 'BMIResult')
      if (Object.keys(BMI).length !== 0) {
        const defaultVal = {
          '偏轻': 0,
          '均值': 0,
          '肥胖': 0,
          '偏重': 0,
          '超重': 0
        }
        for (let key in defaultVal) {
          BMI[key] ? defaultVal[key] = BMI[key] : defaultVal[key] = 0
        }
        window.$.each(defaultVal, (key, value) => {
          arr.push({
            name: key,
            value: value
          })
        })
      } else {
        arr = [{ name: '暂无数据', value: 0 }]
      }
      return arr
    },
    MonthGrowthL (StartDate, idx) {
      const res = this.growthL.data
      let sexv = 0
      let gradev = 1
      switch (this.growthL.sex) {
        case '女童':
          sexv = 0
          break
        case '男童':
          sexv = 1
          break
      }
      switch (this.growthL.grade) {
        case '托班':
          gradev = 1
          break
        case '小班':
          gradev = 2
          break
        case '中班':
          gradev = 3
          break
        case '大班':
          gradev = 4
          break
      }
      const result = res.filter((p) => {
        return p.Gender === sexv && p.GradeNum === gradev
      })
      const data = this.avgHW(result, sexv, parseInt(this.gardenId))
      this.dataList[idx].title = StartDate.split('-')[1] + '月份'
      this.dataList[idx].data = data
    },
    // 最近一段时间
    timeSlot (d, i) {
      const res = timeSlot(d)
      switch (i) {
        case 211:
          this.growthC.time.startTime = res.t1
          this.growthC.time.endTime = res.t2
          break
        case 212:
          this.growthL.time.startTime = res.t1
          this.growthL.time.endTime = res.t2
          break
      }
    },
    // 开始结束时间(天)
    getData (d, i) {
      const res = d[0]
      switch (i) {
        case 211:
          this.growthC.time.startTime = res.t1
          this.growthC.time.endTime = res.t2
          break
      }
    },
    // 城市多选
    getCheckBox (d, i) {
      const res = d[0]
      switch (i) {
        case 212:
          this.growthL.cityList = res
          break
      }
    },
    // 开始结束时间(月)
    getMonthRange (d, i) {
      const res = d[0]
      switch (i) {
        case 212:
          this.growthL.time.startTime = res.t1
          this.growthL.time.endTime = res.t2
          break
      }
    },
    // 城市单选
    getRadio (d, i) {
      const res = d[0]
      switch (i) {
        case 211.1:
          this.growthC.sex = res
          break
        case 211.2:
          this.growthC.grade = res
          break
        case 212.1:
          this.growthL.sex = res
          break
        case 212.2:
          this.growthL.grade = res
          break
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.echarts-box > div
  display flex
  flex-direction column
  height 50%
  .bar
    flex 1
</style>
